﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

public static class SimpleMeshGenerator
{
    [MenuItem("自定义工具/Mesh生成/生成简单平面")]
    static void GenerateSimplePlane()
    {
        Mesh planeMesh = new Mesh();
        planeMesh.name = "SimplePlane";

        /** Unity自带的平面是 10 X 10 大小的，所以我们也创建同样大小的平面 */
        Vector3[] vertices = new Vector3[4];
        vertices[0] = new Vector3(-5f, 0, -5f);
        vertices[1] = new Vector3(-5f, 0, 5f);
        vertices[2] = new Vector3(5f, 0, 5f);
        vertices[3] = new Vector3(5f, 0, -5f);

        int[] indices = new int[6];
        indices[0] = 0;
        indices[1] = 1;
        indices[2] = 2;
        indices[3] = 0;
        indices[4] = 2;
        indices[5] = 3;

        planeMesh.vertices = vertices;
        planeMesh.triangles = indices;

        planeMesh.RecalculateNormals();
        planeMesh.RecalculateBounds();

        SaveMeshToFile(planeMesh);
    }

    const string MeshExportDirectory = "Common/Mesh/Generated";
    static void SaveMeshToFile(Mesh mesh)
    {
        string targetDirectoryPath = Path.Combine(Application.dataPath, MeshExportDirectory);
        if(!Directory.Exists(targetDirectoryPath))
        {
            Directory.CreateDirectory(targetDirectoryPath);
        }

        string targetAssetPath = "Assets/" + MeshExportDirectory + "/" + mesh.name + ".asset";
        if(AssetDatabase.LoadAssetAtPath<Mesh>(targetAssetPath) != null)
        {
            AssetDatabase.DeleteAsset(targetAssetPath);
        }

        AssetDatabase.CreateAsset(mesh,targetAssetPath);
        AssetDatabase.SaveAssets();
    }
}
